<template>
<!-- 广告组 -->
<a-card :border='false'>
  <div>
    <!-- 查询 -->
    <my-table-screen
      :queryParam="queryParam"
      :queryOptions="queryOptions"
      :queryData="queryData"
      @handleFilter="handleFilter"
    ></my-table-screen>
    <div>
      <!-- table -->
      <my-table
        ref="mytable"
        :tableData="tableData"
        :tableLoading="tableLoading"
        @sortChange="sortChange"
        @tableHandleOut="tableHandleOut"
        @tableHandleIn="tableHandleIn"
        @switchChange="switchChange"
      ></my-table>
      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParam.page"
        :limit.sync="queryParam.page_size"
        @pagination="getList"
      />
    </div>

    <!-- 弹窗 -->
      <a-modal
        :title="visibleTitle"
        :confirm-loading="confirmLoading"
        :visible="visible"
        width="50%"
        :maskClosable="false"
        @ok="subimtData"
        @cancel="close"
      >
        <a-spin tip="Loading..." :spinning="is_Loading">
          <my-form
            ref="myform"
            :formData="formData"
            :formBox="formBox"
            :formOptions="formOptions"
            @subimt="subimt"
          ></my-form>
        </a-spin>
      </a-modal>
  </div>

</a-card>
</template>

<script>
import { getCampaignList,getCampaignDetails,campaignAdd,updateStatus,campaignSync } from "@/api/adv/campaign";
import { getAccountListGet } from "@/api/adv/account";

const syncformBox = {
  rules: {
    account_id: [{ required:true, message:'请选择至少一个账号',trigger:'change' }],
  },
  directions:'同步时间与数量相关,确认后将自动同步,请耐心等待',
  formItem:[
    { type:'select',prop:'account_id',label:'广告组账户',placeholder:"请选择广告组账户",options:'putAccount',
      isMultiple:'multiple'
    },
  ]
}

export default {
  data () {
    return {
      is_Loading:false,
      tableLoading:false,
      // 查询
      form_item:{
        rules: {
          name: [{ required:true, message:'请填写广告组名称',trigger:'change' }],
          account_id:[{ required:true,message:'请填写广告组账户',trigger:'change' }],
          // status:[{ required:true,message:'请填写',trigger:'change' }],
          landing_type:[{ required:true,message:'请填写推广目的',trigger:'change' }],
        },
        formItem:[
          {type:'radioGroup',prop:'landing_type',label:'推广目的',
            forRadio:()=> { return this.$global.landingType },
          },
          {type:'radioGroupMoving',prop:'budget_mode',label:'广告组预算',
            forRadio:()=>{ return  this.$global.budgetType },
            moving:true,movingItem:'BUDGET_MODE_DAY',movingProp:'budget'
          },
          {type:'radioGroup',prop:'delivery_related_num',label:'广告组商品类型',
            forRadio:()=> { return this.$global.deliveryType },
          },
          {type:'text',prop:'name',label:'广告组名称',placeholder:'请输入广告组名称'},
          // { type:'select',prop:'status',label:'广告组状态',default:true,options:'status' },
          // { type:'switch',prop:'status',label:'广告组状态',default:true },
          {type:'select',showSearch:true,prop:'account_id',isMultiple:'multiple',label:'广告组账户',placeholder:"请选择广告组账户(多选账号批量创建)",options:'putAccount'},
          
        ]
      },
      queryParam:{  // 初始化数据
        map_status:'CAMPAIGN_STATUS_NOT_DELETE',
        page:1,
        page_size:10
      },
      total: 0,
      queryData:[
        { id:'account_id',title:'投放账户',type:'select',placeholder:'请选择投放账户',options:'putAccount',showSearch:true },
        { id:'keyWord',title:'关键词搜索',type:'input',placeholder:'支持ID或名称搜索' },
        { id:'map_status',title:'广告组状态',type:'select',placeholder:'请选择广告组状态',options:'campaignStatus' },
        { id:'landing_type',title:'推广目的',type:'select',placeholder:'请选择广告组推广目的',options:'landingType' },
        { id:'budget_mode',title:'广告组预算类型',type:'select',placeholder:'请选择广告组预算类型',options:'budgetType' },
        { id:'created_at',title:'创建时间',type:'times' },
      ],
      queryOptions:{
        campaignStatus:this.$global.campaignStatus,
        landingType:this.$global.landingType,
        budgetType:this.$global.budgetType,
        putAccount:[],
      },
      // 表格
      tableData:{
        rowSelection:false,
        batchAction:[ 
          { title:'同步广告组',item:'primary',tableFnc:'handleSyac',icon:'sync' },
          { title:'新建广告组',item:'primary',tableFnc:'handleAdd' }
        ],
        tableDataSource:[],
        tableColumns:[
          { dataIndex:'status',align:'center',scopedSlots: {customRender:'switch'},width:80,
            api:process.env.VUE_APP_ADV_OCEAN_API,postType:'ocean/account',fixed:'left',
            off:'CAMPAIGN_STATUS_DISABLE',run:'CAMPAIGN_STATUS_ENABLE'
          },
          { title:'ID',dataIndex:'id',align:'center',fixed:'left',width:180 },
          { title:'账户ID',dataIndex:'account_id',align:'center',fixed:'left',width:180 },
          { title:'昵称',dataIndex:'name',align:'center',fixed:'left',width:200 },
          { title:'广告组状态',align:'center',width:150,scopedSlots: {customRender:'filter'},
            off:'CAMPAIGN_STATUS_DISABLE',run:'CAMPAIGN_STATUS_ENABLE',
            formatter:(row)=>{
              for (const item of this.$global.campaignStatus) {
                if( item.value == row.status) return item.label
              }
            },colorEvent:(row)=>{
              if(row.status == 'CAMPAIGN_STATUS_ENABLE'){ return `color:${ this.$global.colorStatus['green'] }` }
              else if(row.status == 'CAMPAIGN_STATUS_DISABLE'){ return `color:${ this.$global.colorStatus['orange'] }` }
              else if(row.status == 'CAMPAIGN_STATUS_DELETE'){ return `color:${ this.$global.colorStatus['red'] }` }
            }
          },
          { title:'广告组预算',dataIndex:'budget',align:'center',width:200,scopedSlots: {customRender:'filter'},
            formatter:(row)=>{
              if( row.budget === 0 ) return '不限'
              else return `( 日预算 ) ${row.budget}`
            }
          },
          { title:'广告组预算类型',dataIndex:'budget_mode',align:'center',width:180,scopedSlots: {customRender:'filter'},
            formatter:(row)=>{
              for (const item of this.$global.budgetType) {
                if( item.value == row.budget_mode) return item.label
              }
            }
          },
          { title:'广告组推广目的',dataIndex:'landing_type',align:'center',width:180,scopedSlots: {customRender:'filter'},
            formatter:(row)=>{
              for (const item of this.$global.landingType) {
                if( item.value == row.landing_type) return item.label
              }
            }
          },
          { title:'消耗',dataIndex:'cost',align:'center',width:100,sorter:true },
          { title:'点击数',dataIndex:'click',align:'center',width:100 },
          { title:'展示数',dataIndex:'show',align:'center',width:100 },
          { title:'转化数',dataIndex:'convert',align:'center',width:100 },
          { title:'点击成本',dataIndex:'click_cost',align:'center',width:100 },
          { title:'点击率',dataIndex:'click_rate',align:'center',width:100 },
          { title:'转化成本',dataIndex:'convert_cost',align:'center',width:100 },
          { title:'转化率',dataIndex:'convert_rate',align:'center',width:100 },
          { title:'创建时间',dataIndex:'created_at',align:'center',width:180,sorter:true },
          { title:'更新时间',dataIndex:'updated_at',align:'center',width:180 },
          {
            title: '操作',align:'center',fixed:'right',width:100,
            scopedSlots: {customRender: 'action'},
            tableBtn:[
              { title:'详情',type:'primary',btnType:'handleDetails',size:'small' },
            ]
          },
        ]
      },
      // 弹窗
      formData:{},
      formBox:{},
      formOptions:{   //select数据
        putAccount:[],
        status:this.$global.campaignStatus
      },
      visibleTitle:'',
      confirmLoading:false,
      visible:false,
      // 选项
      checkData:[]
    }
  },
  created () {
    this.getList()
    this.getAccount()
  },
  watch:{
    'queryParam':{
      deep:true,
      immediate:true,
      handler(params){
        let _status = []
        if( params.map_status === "CAMPAIGN_STATUS_NOT_DELETE" ) _status = [ 'CAMPAIGN_STATUS_ENABLE','CAMPAIGN_STATUS_DISABLE' ] // 所有不包含已删除 
        else if( params.map_status === "CAMPAIGN_STATUS_ALL" ) _status = [  ]   // 所有包含已删除 
        else if( params.map_status !== undefined )  _status.push( params.map_status )
        this.queryParam.status = _status
      }
    }
  },
  methods: {
    // 初始化数据
    async getList(){
      this.tableLoading = true
      const res = await getCampaignList(this.queryParam)
      if(res.code === 'SUCCESS') this.tableData.tableDataSource = res.data.list,this.total = res.data.page_info.total
      this.tableLoading = false
    },
    // 投放账户
    getAccount(){
      getAccountListGet( { status:'ENABLE' } ).then((res)=>{
        this.queryOptions.putAccount = this.$selectOptions(res.data,false,true,'account_id')
        this.formOptions.putAccount = this.$selectOptions(res.data,false,true,'account_id')
      })
    },
    // 表格头部按钮
    tableHandleOut(tableFnc){
      if( tableFnc === 'handleAdd' ){   // 新建广告组
        let formItems = this.$deepCopy(this.form_item)
        formItems.formItem.push( { type:'switch',prop:'status',label:'广告组状态',default:true } )
        this.formBox = formItems
        let obj = { name:'', status:true, landing_type:'', budget_mode:'BUDGET_MODE_INFINITE'}
        this.formData = Object.assign({}, obj)
        this.visibleTitle = '新建广告组'
        this.visible = true
      }else if ( tableFnc === 'handleSyac' ){  // 同步
        this.formBox = syncformBox
        this.formData = Object.assign({}, {})
        this.visibleTitle = '同步广告账号'
        this.visible = true
      }
    },
    // 确认
    subimtData(){
      this.is_Loading = true
      if( this.visibleTitle === '新建广告组' || this.visibleTitle === '同步广告账号' ){
        this.$refs.myform.submitForm()
      }else {
        this.close()
      }
    },
    async subimt(formData){
      let res = ''
      if( this.visibleTitle === '新建广告组' ){
        let account_ids = formData.account_id
        let quest = this.$deepCopy(formData)
        for (let i = 0; i < account_ids.length; i++) {
          quest.advertiser_id = account_ids[i]
          res = await campaignAdd(quest.advertiser_id,quest)
          if( res.code !== 'SUCCESS' ) this.$Tip(res)
        }
        this.getList()
        this.visible = false
      }else if ( this.visibleTitle === '同步广告账号' ){
        res = await campaignSync(formData.account_id)
        this.$Tip(res)
        if( res.code === 'SUCCESS' ) this.getList(),this.visible = false
      }
      this.is_Loading = false
    },
    // 关闭弹窗
    close(){
      this.visible = false
    },
    // table表内列按钮
    async tableHandleIn(tableFnc,row){
      if( tableFnc === 'handleDetails' ){
        let formItems = this.$deepCopy(this.form_item)
        formItems.formItem.push( { type:'select',prop:'status',label:'广告组状态',default:true,options:'status' } )
        this.formBox = formItems

        const res = await getCampaignDetails(row.id)
        this.formData = Object.assign({}, res.data)
        this.visibleTitle = '广告组详情'
        this.visible = true

      }
    },
    // 广告组状态 启用、暂停
    switchChange(row,item,index){
      let param = {
        advertiser_id:row.account_id,
        campaign_ids:[row.id],
        opt_status:''
      }

      if(row.status === 'CAMPAIGN_STATUS_ENABLE') param.opt_status ='disable'
      else if (row.status === 'CAMPAIGN_STATUS_DISABLE') param.opt_status ='enable'

      updateStatus(row.account_id,param).then((res)=>{
        if(res.code === 'SUCCESS'){
          this.tableData.tableDataSource[index].status = param.opt_status === 'disable' ? 'CAMPAIGN_STATUS_DISABLE' : 'CAMPAIGN_STATUS_ENABLE'
        }
      })
    },
    // 排序
    sortChange(sorter){
      const { field, order } = sorter
      this.queryParam.order_by = field
      this.queryParam.order_type = order === 'ascend' ? 'asc' : 'desc'
      this.handleFilter()
    },
    // 查询
    handleFilter(){
      this.queryParam.page = 1
      this.getList()
    },
  }
}
</script>
